import { AnyAction } from "redux";
import produce from "immer";
import { userInfoResDTO } from "@/api/base/login";
import { RoleEnum } from "@/enums/roleEnum";

interface UserState {
	userInfo: Nullable<userInfoResDTO>;
	accessToken?: string;
	refreshToken?: string;
	roleList: RoleEnum[];
	sessionTimeout?: boolean;
	lastUpdateTime: number;
}

const authState: UserState = {
	// user info
	userInfo: null,
	// token
	accessToken: undefined,
	refreshToken: undefined,
	// roleList
	roleList: [],
	// Whether the login expired
	sessionTimeout: false,
	// Last fetch time
	lastUpdateTime: 0
};

const user = (state: UserState = authState, action: AnyAction) =>
	produce(state, draftState => {
		switch (action.type) {
			case "set_user_info":
				draftState.userInfo = action.payload;
				break;
			case "set_access_token":
				draftState.accessToken = action.payload;
				break;
			case "set_refresh_token":
				draftState.refreshToken = action.payload;
				break;
			case "set_role_list":
				draftState.roleList = action.payload;
				break;
			case "set_session_timeout":
				draftState.sessionTimeout = action.payload;
				break;
			default:
				return draftState;
		}
	});

export default user;
